package com.doublefish.doublefishrobot.ui.video.widget;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.VideoView;

import androidx.annotation.Nullable;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.ui.video.bean.VideoPlayerItemBean;
import com.doublefish.doublefishrobot.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 作者:dugaofeng on 2024/10/29 14:46
 */
public class VideoPlayerView extends FrameLayout implements VideoPlayerControlView.OnVideoPlayerControlViewListner {

    private VideoPlayerControlView videoPlayerControlView;
    private ProgressBar progressBar;

    private VideoPlayerItemBean videoPlayerItemBean = null;
    private String videoPlayerPath = "";
//    private boolean isShowing = false; //默认不显示

    private Timer timer;
    private static int PROGRESS_INTERVAL = 200;  //获取进度条的间隔时间 毫秒
    private static int TIME_OUT = 5000;  //控件自动隐藏的默认时间 毫秒
    private int timeout = TIME_OUT; // 控件自动隐藏的时间

    private OnVideoPalyerViewListner onVideoPalyerViewListner;
    private boolean needSeek = false;
    private int seekPosition;

    private VideoView videoView;
    private MediaPlayer mediaPlayerRef;
    private boolean didPrepare = false;
    private int duration = 0;
    private int curPos = 0;

    public VideoPlayerView(Context context) {
        this(context, null);
    }

    public VideoPlayerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoPlayerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public VideoPlayerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    private void initView() {
        inflate(getContext(), R.layout.view_mode_video, this);

        videoPlayerControlView = findViewById(R.id.video_player_control);
        videoPlayerControlView.setVisibility(INVISIBLE);
        videoPlayerControlView.setOnVideoPlayerControlViewListner(this);

        progressBar = findViewById(R.id.loading_progress);

        videoView = findViewById(R.id.video_view);
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                didPrepare = true;
                timeout = TIME_OUT;
                videoPlayerControlView.setVisibility(VISIBLE);
                mediaPlayer.setLooping(true);
//                mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
                mediaPlayerRef = mediaPlayer;

                duration = videoView.getDuration();
                start();
           }
       });

        videoView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                showOrHideControlView();
            }
        });
    }

    public void setOnVideoPalyerViewListner(OnVideoPalyerViewListner onVideoPalyerViewListner) {
        this.onVideoPalyerViewListner = onVideoPalyerViewListner;
    }

    //特殊情况 按下系统的返回键 退出全屏
    public void exitFullScreen() {
        videoPlayerControlView.exitFullScreen();
    }

    public void setVideoPlayerItemBean(VideoPlayerItemBean videoPlayerItemBean) {
        if (videoPlayerItemBean == null) {
            ToastUtil.showToast(getContext(), getContext().getString(R.string.error_video_info));
            return;
        }
//        if (this.videoPlayerItemBean != null
//        && this.videoPlayerItemBean.getUrl().equals(videoPlayerItemBean.getUrl())) {
//            //注意：这里虽然bean的数据发生了变化，但是对于播放器来来说，地址没有变，还是可以正常播放
//            //为了拿到最新的下载进度
//            this.videoPlayerItemBean = videoPlayerItemBean;
//            return;
//        }
//
//        //视频名没有变 说明替换了源地址
//        if (this.videoPlayerItemBean != null
//                && this.videoPlayerItemBean.getVideoCode() != null
//                &&this.videoPlayerItemBean.getVideoCode().length() != 0
//                && this.videoPlayerItemBean.getVideoCode().equals(videoPlayerItemBean.getVideoCode())) {
//            //需要seek到原来的位置
//            this.needSeek = true;
//        }
//        this.videoPlayerItemBean = videoPlayerItemBean;

        if (this.videoPlayerItemBean != null
                && this.videoPlayerItemBean == videoPlayerItemBean) {
            //同一个数据模型 注意：这里虽然bean的数据发生了变化，但是对于播放器来来说，播放源地址没有变，还是可以正常播放
            if (this.videoPlayerPath.equals(videoPlayerItemBean.getUrl())) {
                Log.i("videoPlayerItemBean", "progress= " + videoPlayerItemBean.getProgress());
                return;
            }
            //播放源地址变化
            // 需要seek到原来的位置
            this.needSeek = true;
        }
        this.videoPlayerItemBean = videoPlayerItemBean;
        this.videoPlayerPath = videoPlayerItemBean.getUrl();
        hideLoading();

        try {
            if (this.needSeek) {
                this.seekPosition = getCurrentPosition();
            }
            stop();
            videoView.setVideoPath(videoPlayerItemBean.getUrl());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        if (videoPlayerItemBean == null) {
//            测试视频
//            videoPath = "http://vjs.zencdn.net/v/oceans.mp4";
            return;
        }
        if (!didPrepare) {
            return;
        }

        //开始播放
        videoView.start();
        startTimer();
        if (needSeek) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (needSeek) {
                        needSeek = false;
                        seekTo(seekPosition);
                    }
                }
            }, 200);
        }
    }

    public void pause() {
        if (videoView.isPlaying()) {
            videoView.pause();
        }
    }

    //恢复播放
    public void resume() {
        if (!videoView.isPlaying()) {
            //resume 从头开始播放
//            videoView.resume();
            //start 继续播放
            videoView.start();
        }
    }

    public void stop() {
        stopTimer();
        didPrepare = false;
        if (videoView.isPlaying()) {
            videoView.stopPlayback();
        }
    }

    public void setSpeed(int postion) {
        String text = speedList().get(postion);
        float speed = 1.0f;
        switch (postion) {
            case 0:
                speed = 0.5f;
                break;
            case 1:
                speed = 0.8f;
                break;
            case 2:speed = 1.0f;
                break;
            case 3:
                speed = 1.25f;
                break;
            case 4:
                speed = 1.5f;
                break;
            case 5:
                speed = 2.0f;
                break;
        }
        videoPlayerControlView.setSpeed(text);
        if (mediaPlayerRef == null) {
            return;
        }
        mediaPlayerRef.setPlaybackParams(mediaPlayerRef.getPlaybackParams().setSpeed(speed)); // 设置播放速度
    }

    public List<String> speedList() {
        List<String> list= new ArrayList<>();
        list.add("x0.5");
        list.add("x0.8");
        list.add("x1.0");
        list.add("x1.25");
        list.add("x1.5");
        list.add("x2.0");
        return list;
    }

    public int getCurrentPosition() {

//        if (videoView.isPlaying()) {
//            curPos = videoView.getCurrentPosition();
//        }

        try {
            curPos = videoView.getCurrentPosition();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curPos;
    }

    private int getDuration() {
        return duration;
    }

    public void seekTo(int currentPosition) {
        try {
            videoView.seekTo(currentPosition);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //region 定时器
    private void startTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timerAction();
            }
        }, 0, PROGRESS_INTERVAL);
    }

    public void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void timerAction() {
        //自动隐藏 (200ms/每次)
        if (timeout > 0) {
            timeout -= PROGRESS_INTERVAL;
            if (timeout <= 0) {
                videoPlayerControlView.setVisibility(INVISIBLE);
            }
        }
        long duration = getDuration();
        long cur = getCurrentPosition();
        videoPlayerControlView.setPlayTime(cur, duration);

        if (videoPlayerItemBean == null) {
            return;
        }

        if (videoPlayerItemBean.getAVPlayerItemType() == VideoPlayerItemBean.DFAVPlayerItemDownloadAndPlay) {
            //边下边播
            float curProgress =  cur * 100.0f / duration;  //当前视频进度
            //已下载的进度
            long size = videoPlayerItemBean.getSize();
            //视频下载进度
            int downloadProgress = videoPlayerItemBean.getProgress();

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    videoPlayerControlView.setCacheProgress(downloadProgress);
                    //小于5% 说明刚开始播放
                    if (downloadProgress < 5) {
                        return;
                    }

//                    播放状态下  最少要有%10缓冲（低于10% 就暂停 等待缓冲）
//                    暂停状态下 最少要有%20缓冲（高于20%，继续播放）
                    float offset = videoView.isPlaying() ? 15 : 30;
                    if (downloadProgress < 100 && curProgress + offset > downloadProgress) {
                        pause();
                        showLoading();
                    } else {
                        resume();
                        hideLoading();
                    }
                }
            });
        } else {
            videoPlayerControlView.setCacheProgress(100);
        }
    }

    private void showLoading() {
        if (progressBar.getVisibility() != VISIBLE) {
            progressBar.setVisibility(VISIBLE);
        }
    }

    private void hideLoading() {
        if (progressBar.getVisibility() != GONE) {
            progressBar.setVisibility(GONE);
        }
    }

    private void showOrHideControlView() {
        if (videoPlayerControlView.getVisibility() == VISIBLE) {
            timeout = 0;
            videoPlayerControlView.setVisibility(INVISIBLE);
        } else {
            timeout = TIME_OUT;
            videoPlayerControlView.setVisibility(VISIBLE);
        }
    }

    //endregion


    //region  VideoPlayerControlView.OnVideoPlayerControlViewListner

    @Override
    public void onPlayBtnClick(boolean play) {
//        if (mediaPlayer == null) {
//            return;
//        }
        if (!videoView.isPlaying()) {
            videoView.start();
        } else {
            videoView.pause();
        }
    }

    @Override
    public void onFullScreenBtnClick(boolean fullScreen) {
        if (onVideoPalyerViewListner != null) {
            onVideoPalyerViewListner.onFullScreenBtnClick(fullScreen);
        }
    }

    @Override
    public void onSeekbarSeeking() {
        timeout = TIME_OUT;
    }

    @Override
    public void onSeekbarChanged(int progress) {
        if (videoPlayerItemBean.getAVPlayerItemType() == VideoPlayerItemBean.DFAVPlayerItemDownloadAndPlay) {
            //边下边播
            //已下载的进度
//            long size = videoPlayerItemBean.getSize();
            //视频下载进度
            long downloadProgress = videoPlayerItemBean.getProgress();
            if (downloadProgress < 100 && progress + 15 > downloadProgress) {
                ToastUtil.showToast(getContext(), "正在缓冲中...");
            }
            return;
        }
        int duration = getDuration();
        int pos = duration * progress / 100;
        seekTo(pos);
    }

    @Override
    public void onSpeedBtnClick() {
        if (onVideoPalyerViewListner != null) {
            onVideoPalyerViewListner.onSpeedBtnClick();
        }
    }
    //endregion

    //region  OnVideoPalyerViewListner
    public interface OnVideoPalyerViewListner {
        void onFullScreenBtnClick(boolean fullScreen);
        void onSpeedBtnClick();
    }

    //endregion

}